package admin

import (
	ct "context"
	"encoding/json"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	. "xm_shop/database"
	. "xm_shop/models"
	pb "xm_shop/proto/rbacRole"
)

type MainController struct{}

// 控制不同用户显示的内容
func (m MainController) Index(context *gin.Context) {
	// 获取session
	session := sessions.Default(context)
	userInfo := session.Get("userInfo") // type: interface{}
	// 断言
	userInfoStr, ok := userInfo.(string)
	// 转成结构体切片
	if ok {
		// 1. 获取用户信息
		var userInfoStruct []Manager
		json.Unmarshal([]byte(userInfoStr), &userInfoStruct)
		// 调用微服务获取当前角色展示的菜单
		rbacClient := pb.NewRbacRoleService("rbac", MicroClient)
		res, _ := rbacClient.RoleAuth(ct.Background(), &pb.RoleAuthRequest{
			Id: int64(userInfoStruct[0].ID),
		})
		context.JSON(http.StatusOK, gin.H{
			"userInfo":   userInfoStruct,
			"accessList": res.AccessList,
			"isSuper":    userInfoStruct[0].IsSuper,
		})
	} else {
		context.String(http.StatusOK, "跳转到登录界面")
	}
}

// 公共修改状态的方法
func (m MainController) ChangeStatus(context *gin.Context) {
	id, err1 := strconv.Atoi(context.Param("id"))
	if err1 != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"msg":     "参数有误",
		})
		return
	}
	// 获取 table 指定哪张表
	table := context.PostForm("table")
	// 获取 field 指定哪个字段
	field := context.PostForm("field")
	// 执行原始SQL更新
	// update focus set status=ABS(status-1) where id=1
	err2 := DB.Exec("update "+table+" set "+field+"=ABS("+field+"-1) where id=?", id).Error
	if err2 != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"msg":     "修改失败",
		})
		return
	}
	context.JSON(http.StatusOK, gin.H{
		"success": true,
	})
}

// 公共修改sort的方法
func (m MainController) ChangeSort(context *gin.Context) {
	// 获取路径参数
	id, err1 := strconv.Atoi(context.Param("id"))
	if err1 != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"msg":     "参数有误",
		})
		return
	}
	// 获取表名
	table := context.PostForm("table")
	// 获取字段名
	field := context.PostForm("field")
	// 获取到sort
	sort := context.PostForm("sort")
	err2 := DB.Exec("update "+table+" set "+field+"="+sort+" where id=?", id).Error
	if err2 != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"msg":     "修改失败",
		})
		return
	}
	context.JSON(http.StatusOK, gin.H{
		"success": true,
	})
}

// 清除redis缓存
func (m MainController) FlushAll(context *gin.Context) {
	CacheDB.FlushAll()
	context.String(http.StatusOK, "缓存清除成功")
}
